package com.cyp.productservice.service;

import com.cyp.productservice.entity.Product;
import com.cyp.productservice.mapper.ProductsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class ProductService {

    @Autowired
    private ProductsMapper productMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    public List<Product> getProductList(){
        return productMapper.getProductList();
    }
    public Product getProductById(Long id){
        return productMapper.selectById(id);
    }
    public int updateProduct(int quantity,Long id,Long userId){
        Product product = productMapper.selectById(id);
        int stock =product.getStock()-quantity;
        if (stock<0){
            return -1;
        }
        product.setStock(product.getStock()-quantity);
        //存redis
        Long add = redisTemplate.opsForSet().add("product:" + id, userId);

        log.info("productRedis::.{}",redisTemplate.keys("product:"+id));
        return productMapper.updateById(product);
    }
    public List<Map<String, Object>> getRedis(){
        Set<String> keys = redisTemplate.keys("*");
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> data = new HashMap<>();
        for (String key : keys) {
            data.put(key, redisTemplate.opsForSet().members(key));
            list.add(data);
        }
        log.info("productRedisList::.{}",list);
        return list;
    }

}
